package com.aliwo.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliwo.enums.ScriptTypeEnum;
import com.aliwo.exception.ControllerException;
import com.aliwo.request.SaveScriptJobInfoRequest;
import com.aliwo.service.ScriptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author:xuyayuan
 * @date:2021/7/26 13:31
 * @description:TODO
 */
@SuppressWarnings("all")
@Api(tags = "脚本处理器模块")
@RestController
@RequestMapping("/powerjob/script")
public class ScriptController {

    @Autowired
    private ScriptService scriptService;

    @ApiOperation("httpApi新增任务")
    @PostMapping("/save")
    public ResponseEntity<Long> saveApiJobInfo(@ApiParam(value = "httpAIP创建任务请求对象") @RequestBody SaveScriptJobInfoRequest
                                                       saveScriptJobInfoRequest) throws Exception {
        preValid(saveScriptJobInfoRequest);
        Long resultDTO = scriptService.saveScriptJob(saveScriptJobInfoRequest);
        return ResponseEntity.ok(resultDTO);
    }

    /**
     * 功能描述: 创建任务参数，校验
     *
     * @param saveHttpJobInfoRequestrequest
     * @return void
     * @author xuyayuan
     */
    private void preValid(SaveScriptJobInfoRequest saveScriptJobInfoRequest) {
        saveScriptJobInfoRequest.valid();

        Optional.ofNullable(saveScriptJobInfoRequest.getScriptType())
                .orElseThrow(() -> new ControllerException("APP:SCHEDULE:API_JOB_SAVE", "scriptType不能为空",
                        "ControllerException.schedule.info.scriptType_notEmpty"));
        // shell处理器
        if (ScriptTypeEnum.SHELL_TYPE.getScriptType().equals(saveScriptJobInfoRequest.getScriptType())) {
            saveScriptJobInfoRequest.setJobParams(saveScriptJobInfoRequest.getScriptContext());
            saveScriptJobInfoRequest.setProcessorInfo("tech.powerjob.official.processors.impl.script.ShellProcessor");
        }
        // python处理器
        if (ScriptTypeEnum.PYTHOn_TYPE.getScriptType().equals(saveScriptJobInfoRequest.getScriptType())) {
            saveScriptJobInfoRequest.setJobParams(saveScriptJobInfoRequest.getScriptContext());
            saveScriptJobInfoRequest.setProcessorInfo("tech.powerjob.official.processors.impl.script.PythonProcessor");
        }
    }


}
